//
//  AskViewController.m
//  DesighBook
//
//  Created by 梅明 on 15/9/18.
//  Copyright (c) 2015年 梅明. All rights reserved.
//

#import "AskViewController.h"
#import "CExpandHeader.h"
#import "AskButtonView.h"
#import "NetInterface.h"
#import "HttpRequestManager.h"
#import "AskModel.h"
#import "CustomTableViewCell.h"
#import "UIImageView+AFNetworking.h"
#import "AskDetaiViewController.h"
#define NavigationBarHight 64.0f

#define ImageHight 200.0f
#define viewwidth self.view.frame.size.width
#define viewheight self.view.frame.size.height
@interface AskViewController ()<UITableViewDataSource,UITableViewDelegate>
{
    UIImageView *_zoomImageView;//变焦图片做底层
    UIImageView *_titleView;//顶端文字图片
    UIButton *_titleButton; //顶端的button
//    CExpandHeader *_header;
    UIImageView *_expandView; //顶端放大图片
    AskButtonView *_buttonView; //三个按钮选项view
    UIView *_downview; //button下得红色线条
    int _select; //button的选择状态
    NSString *_url;  //请求网址
    NSMutableArray *_dataArray;
    
    
    CGFloat _oldcontenoffset;
}
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@end

@implementation AskViewController
- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super initWithCoder:coder];
    if (self) {
        _select = 0;
        _dataArray = [[NSMutableArray alloc]init];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    [self createExpandpic];
    [self createButtonview];
    [self judgePage];
    
    
    _buttonView.block = ^(int i ){
        _select = i-100;
        _downview = [[UIView alloc]initWithFrame:CGRectMake(_select*viewwidth/3, 38, viewwidth/3, 2)];
        [self judgePage];
    };
    
}
//判断button的选择状态
-(void)judgePage
{
    switch (_select) {
        case 0:
            _url = active_url;
            break;
        case 1:
            _url = ask_url;
            break;
        case 2:
            _url = answer_url;
            break;
            
        default:
            break;
    }
    [self loadDataFromNet];
}

//从网络请求数据
-(void)loadDataFromNet
{
    [_dataArray removeAllObjects];
    [[HttpRequestManager shareInstnce]getAskInfoWithurl:_url AndSuccess:^(id responseObjec) {
        NSArray *arr = responseObjec;
        for (NSDictionary *dic in arr) {
            AskModel *model = [[AskModel alloc]init];
            NSNumber *num = dic[@"comments"];
            model.comments = num.stringValue;
            model.createTime = dic[@"createTime"];
            model.desc = dic[@"desc"];
            num = dic[@"hits"];
            model.hits = num.stringValue;
            num = dic[@"id"];
            model.numberid = num.stringValue;
            model.title = dic[@"title"];
            model.imgurl = dic[@"imgUrl"];
            [_dataArray addObject:model];
        }
        [_myTableView reloadData];
        
    } AndFailure:^(NSError *error) {
        
        NSLog(@"error == %@",error);
    }];
}

-(void)createButtonview
{
    NSArray *titlearray = @[@"最近活跃",@"最新提问",@"等待回答"];
    _buttonView = [[AskButtonView alloc]initWithFrame:CGRectMake(0, 0, viewwidth, 40)];
    NSString *str = @"ask";
    [_buttonView setbuttonWithArray:titlearray AndPage:str];
    _buttonView.userInteractionEnabled = YES;

    [_buttonView addSubview:_downview];
}
-(void)createExpandpic
{
    

    
    //设置contentInset属性（上左下右 的值）
    _myTableView.contentInset = UIEdgeInsetsMake(ImageHight, 0, 0, 0);
    _myTableView.tableFooterView = [[UIView alloc]init];
//    _expandView.image = [UIImage imageNamed:@"bg_qa.jpg"];
    _zoomImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"bg_qa.jpg"]];
    _zoomImageView.frame = CGRectMake(0, -ImageHight, self.view.frame.size.width, ImageHight);
    
    //contentMode = UIViewContentModeScaleAspectFill时，高度改变宽度也跟着改变
    _zoomImageView.contentMode = UIViewContentModeScaleAspectFill;//重点（不设置那将只会被纵向拉伸）
    
    //将_zoomImageView添加到tableview上
        [_myTableView addSubview:_zoomImageView];
    
    //设置autoresizesSubviews让子类自动布局
    _zoomImageView.autoresizesSubviews = YES;
    
    //设置文字图片
    _titleView = [[UIImageView alloc]initWithFrame:CGRectMake(viewwidth/2-100, ImageHight-150, 200, 50)];
    _titleView.image = [UIImage imageNamed:@"bg_font.png"];
    _titleView.clipsToBounds = YES;
    _titleView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;//自动布局，自适应顶部
    [_zoomImageView addSubview:_titleView];
    
    //设置Button
    _titleButton = [[UIButton alloc]initWithFrame:CGRectMake(viewwidth/2-50, ImageHight-80, 100, 30)];
    [_titleButton setBackgroundImage:[UIImage imageNamed:@"bg_myhomepage.jpg"] forState:UIControlStateNormal];
    _titleButton.clipsToBounds = YES;
    [_titleButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    //    _titleButton
    _titleButton.layer.cornerRadius = 5;
    [_titleButton setTitle:@"我要提问" forState:UIControlStateNormal];
    _titleButton.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    _titleButton.titleLabel.font = [UIFont systemFontOfSize:14];
    [_zoomImageView addSubview:_titleButton];

}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    _oldcontenoffset = scrollView.contentOffset.y;
}

//放大效果,上移不用处理,自动上移
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    CGFloat y = scrollView.contentOffset.y;//根据实际选择加不加上NavigationBarHight（44、64 或者没有导航条）
    if (y < -ImageHight) {
        CGRect frame = _zoomImageView.frame;
        frame.origin.y = y;
        frame.size.height =  -y;//contentMode = UIViewContentModeScaleAspectFill时，高度改变宽度也跟着改变
        _zoomImageView.frame = frame;
        
        
    }
    if (scrollView.contentOffset.y>-150) {
        self.navigationController.navigationBar.hidden = NO;
    }
    else
    {
        self.navigationController.navigationBar.hidden = YES;
    }
    

    if ( scrollView.contentOffset.y - _oldcontenoffset>0 &&scrollView.contentOffset.y>-136) {
        _myTableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
    }
    else if(scrollView.contentOffset.y - _oldcontenoffset<0 && scrollView.contentOffset.y<-64)
    
    {
//        _myTableView.contentInset = UIEdgeInsetsMake(-200, 0, 0, 0);
    }
    
}

#pragma mark -UITableViewDataSource,UITableViewDelegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CustomTableViewCell"];
    cell.imgview.image = nil;
    AskModel *model = _dataArray[indexPath.row];
    if (model.imgurl.length == 0) {
        
        cell.imgview.image = [UIImage imageNamed:@"ico_QA_default.jpg"];
    }
    [cell.imgview setImageWithURL:[NSURL URLWithString:model.imgurl]];
    cell.TitleLabel.text = model.title;
    cell.createTimeLabe.text = model.createTime;
    cell.commentLabel.text = model.comments;
    cell.hitlabel.text = model.hits;

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self performSegueWithIdentifier:@"detail4" sender:indexPath];
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"detail4"]) {
        AskDetaiViewController *view = segue.destinationViewController;
        NSIndexPath *path = sender;
        AskModel *model = _dataArray[path.row];
        view.numberid = model.numberid;
    }
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{

    return _buttonView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

@end
